package com.example.dnfgamercommunitybackend.service.impl;

import com.example.dnfgamercommunitybackend.dao.ArticleDao;
import com.example.dnfgamercommunitybackend.dao.ArticleLikesDao;
import com.example.dnfgamercommunitybackend.entity.ArticleLikes;
import com.example.dnfgamercommunitybackend.entity.ResponseResult;
import com.example.dnfgamercommunitybackend.service.ArticleLikesService;
import com.example.dnfgamercommunitybackend.util.JwtUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
@Service
public class ArticleLikesServiceImpl implements ArticleLikesService {
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private ArticleLikesDao articleLikesDao;
    @Resource
    private ArticleDao articleDao;
    @Override
    public String addLike(int articleId, String token) {
        //通过token获取用户id
        int accountId = Integer.parseInt(jwtUtil.getUserIdFromToken(token));
        //检查用户是否已经点过赞
        ArticleLikes articleLikes = new ArticleLikes();
        articleLikes.setAccountId(accountId);
        articleLikes.setArticleId(articleId);
        //点过赞，提示已点过赞
        if (!Objects.isNull(articleLikesDao.existRecord(articleLikes))){
            return ResponseResult.failureStringResult("您已点过赞");
        }
        //未点过赞，增加点赞记录
        try{
            if (articleLikesDao.insertLikeRecord(articleLikes) > 0
                    && articleDao.addLike(articleId) > 0){
                return ResponseResult.successStringResult("点赞成功");
            }
        }catch (Exception e){
            throw new RuntimeException("无此文章id");
        }
        return ResponseResult.failureStringResult("点赞失败");
    }

    @Override
    public String cancelLike(int articleId,String authorization) {
        //获取用户id
        int userId = Integer.parseInt(jwtUtil.getUserIdFromToken(authorization));
        //检查用户是否已经点过赞
        ArticleLikes articleLikes = new ArticleLikes();
        articleLikes.setAccountId(userId);
        articleLikes.setArticleId(articleId);
        articleLikes = articleLikesDao.existRecord(articleLikes);
        if (Objects.isNull(articleLikes)){
            return ResponseResult.failureStringResult(504,"取消失败，未点过赞");
        }
        if (articleLikesDao.cancelLike(articleLikes) > 0){
            //点赞数减去1
            if (articleDao.cancelLike(articleId) > 0){
                return ResponseResult.successStringResult("取消成功");
            }
        }
        return ResponseResult.failureStringResult("取消失败");
    }
}
